var logManager=require("../Logs.js");
var SystemEvent=require("../event/SystemEvent")
var ServerClient=require("./SocketServerClient.js")
var ws = require('nodejs-websocket');
var SocketServer=Class.extend({
    name:"webSocket",
    socketCount:0,
    _port:0,
    _clientSocketDic:null,
    _serverSocket:null,
    eventManager:null,

    ctor(eventManager){
        this.eventManager=eventManager
    },

    listen:function(port,keyData){
        this.close();
        this._port=port;
        this._clientSocketDic={}
        if(keyData) {
            var fs = require('fs');
            var options = {
                key: fs.readFileSync(keyData.key),
                cert: fs.readFileSync(keyData.cert),
                secure:true,
                requestCert: false,
                rejectUnauthorized: true
            }
            this._serverSocket = ws.createServer(options,this.addClientSocket.bind(this));
        }else {
            this._serverSocket = ws.createServer(this.addClientSocket.bind(this))
        }
        this._serverSocket.listen(port);
        this.eventManager.addListener(SystemEvent.SOCKET_CLOSE,this.onSocketClose,this);
        logManager.logM("socket listen on:"+port)
    },
    close:function(){
        if(this._serverSocket)
            this._serverSocket.close();
        this._serverSocket=null;
        this.eventManager.removeListener(SystemEvent.SOCKET_CLOSE,this.onSocketClose,this);
    },
    onSocketClose:function(data){
        logManager.logM("socket close "+data.port+":"+data.clientId)
        if(data.port!=this._port)return;
        if(this._clientSocketDic[data.clientId]) {
            delete this._clientSocketDic[data.clientId];
        }
    },
    closeSocketByClientId:function(clientId){
        if(this._clientSocketDic[clientId]) {
            var tem=this._clientSocketDic[clientId];
            delete this._clientSocketDic[clientId];
            tem.closeSocket();
        }
        logManager.logM("closing socket:"+clientId)
        this.eventManager.dispatchEvent(SystemEvent.SOCKET_CLOSE,[{clientId:clientId}]);
    },
    addClientSocket:function (conn) {
        this.socketCount++;
        var client=new ServerClient(this.socketCount,conn,this._port,this.eventManager)
        this._clientSocketDic[this.socketCount]=client;
        this.eventManager.dispatchEvent(SystemEvent.SOCKET_ADD,[{clientId:this.socketCount,path:conn.path,key:conn.key,headers:conn.headers}]);
        logManager.logM("add websocket client:"+this.socketCount)
    },
    sendMsg:function (clientId,msg) {
        if(clientId<=0){
            for(var key in this._clientSocketDic){
                if(key!=-clientId&&this._clientSocketDic[key]){
                    this._clientSocketDic[key].sendMsg(msg)
                }
            }
            return;
        }
        var client=this._clientSocketDic[clientId];
        if(client)
            client.sendMsg(msg);
    }
})

module.exports=SocketServer